package com.kennedy.springbootjpa.service;

import com.kennedy.springbootjpa.beans.menu.Menu;
import com.kennedy.springbootjpa.repostory.MenuRepository;
import com.kennedy.springbootjpa.utils.DateUtil;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import java.util.ArrayList;
import java.util.List;

import static javafx.scene.input.KeyCode.T;

/**
 * Created by tao.zeng on 2017/8/14.
 */
@Service
public class MenuService {
    @Autowired
    private MenuRepository menuRepository;

    public Page<Menu> getListByPage(Menu menu) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnorePaths("pageNumber", "pageSize");
        Example<Menu> example = Example.of(menu, matcher);
        Page<Menu> menus = menuRepository.findAll(new Specification<Menu>() {
            @Override
            public Predicate toPredicate(Root<Menu> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        }, new PageRequest(menu.getPageNumber() - 1, menu.getPageSize()));
        return menus;
    }

    public void add(Menu menu) {
        menu.setCreateTime(DateUtil.getCurrentTime());
        menuRepository.save(menu);
    }

    public void delete(long id) {
        menuRepository.delete(id);
    }
}
